<?php

namespace app\admin\controller;

use app\admin\model\ProductBatchStock;
use app\admin\model\Store;
use app\admin\model\Member;
use app\admin\model\Stock;
use app\admin\model\Purchase;
use app\admin\model\Order;
use app\admin\model\Orderitem;
use app\admin\model\OrderAfterSale;
use app\admin\model\Product;
use app\admin\model\PurchaseReceivingProduct;
use app\admin\model\Rechargerecord;
use app\admin\model\Memberlevelrecord;

use think\Db;

class Dashboard extends Base
{

    public function index(){
        // 门店
        $stores = Store::where([])->select();
        $this->assign('stores', $stores);

        // 库存不足
        $lowStocks = Stock::where(['marketable' => ['elt', 10]])->count();
        // 要货单
        $countPurchases = Purchase::where(['status' => 1])->count();
        // 退货单
        $countReturnPurchases = 0;
        // 售后退款
        $refundOrder = OrderAfterSale::where(['status' => 1])->count();

        // 项目统计
        $projectStatistics = $this->projectStatistics();

        // 商品数（种）
        $countProducts = Product::where(['status' => 1])->count();
        // 商品库存量
        $countStocks = Stock::where([])->sum('marketable');
        // 30天内过期数量（种）
        //$sql = "SELECT COUNT(*) AS tp_count FROM `product` WHERE `status` = 1 AND datediff(day, now(), create_date)<30 LIMIT 1";
        //$countDeadline = Db::query($sql);
        $deadlineWhere = [];
        $countDeadline = ProductBatchStock::where($deadlineWhere)->whereBetween('deadline', [date('Y-m-d'), date('Y-m-d', time() + 3600*24*30)])->count();
        // 商品销量排名
        $salesRanking = $this->salesStatistics();
        // 商品交易额排名
        $tradeRanking = $this->tradeStatistics();

        // 运营统计
        $operationStatistics = $this->operationStatistics();

        $data = [
            'lowStocks' => $lowStocks,
            'countPurchases' => $countPurchases,
            'countReturnPurchases' => $countReturnPurchases,
            'refundOrder' => $refundOrder,
            'projectStatistics' => $projectStatistics,
            'product' => [
                'countProducts' => $countProducts,
                'countStocks' => $countStocks,
                'countDeadline' => $countDeadline,
                'salesRanking' => $salesRanking,
                'tradeRanking' => $tradeRanking
            ],
            'operationStatistics' => $operationStatistics,
        ];

        $this->assign('data', $data);

        return $this->view->fetch();
    }

    /**
     * Ajax 项目统计
     */
    public function ajaxProjectStatistics(){
        $params = $this->request->param();
        //$startTime = strtotime($params['start_time']);
        //$endTime = strtotime($params['end_time']);
        $data = $this->projectStatistics($params);

        return json($data);
    }

    /**
     * 项目统计
     */
    protected function projectStatistics($params = []){
        $where = [];
        $startMonth = date("Y-m-01");
        $endMonth = date('Y-m-d', strtotime(date("Y-m-01 23:59:59")." +1 month -1 day"));

        $startTime = $startMonth;
        $endTime = $endMonth;
        if(isset($params['range_date'])){
            $rangeDate = explode(' ~ ', $params['range_date']);
            $startTime = $rangeDate[0] . ' 00:00:00';
            $endTime = $rangeDate[1] . ' 23:59:59';
        }

        // ---------- 商品销售 ---------- //
        // 总金额
        $totalOrder = Order::whereBetween('create_date', [$startTime, $endTime])->sum('total');
        // 单数
        $countOrder = Order::whereBetween('create_date', [$startTime, $endTime])->count();
        // 单均价
        $averagePrice = 0;
        if ($totalOrder) {
            $averagePrice = number_format(($totalOrder / $countOrder / 100), 2, '.', '');
        }
        // 余额支付 金额
        $balanceOrder = Order::whereBetween('create_date', [$startTime, $endTime])->where(['pay_method' => 3])->sum('total');
        // 微信支付 金额
        $weixinOrder = Order::whereBetween('create_date', [$startTime, $endTime])->where(['pay_method' => 1])->sum('total');
        // 支付宝支付 金额
        $alipayOrder = Order::whereBetween('create_date', [$startTime, $endTime])->where(['pay_method' => 2])->sum('total');

        // ---------- 钱包充值 ---------- //
        // 总金额
        $totalRecharge = Rechargerecord::whereBetween('create_date', [$startTime, $endTime])->where(['type' => 1, 'pay_method' => 1])->sum('record_money');
        // 赠送金额
        $totalRechargeGift = Rechargerecord::whereBetween('create_date', [$startTime, $endTime])->where(['type' => 1, 'pay_method' => 1])->sum('gift_money');
        // 单数
        $countRecharge = Rechargerecord::whereBetween('create_date', [$startTime, $endTime])->where(['type' => 1, 'pay_method' => 1])->count();
        // 微信支付 金额
        $weixinRecharge = Rechargerecord::whereBetween('create_date', [$startTime, $endTime])->where(['type' => 1, 'pay_method' => 1])->sum('record_money');
        // 支付宝支付 金额
        $alipayRecharge = Rechargerecord::whereBetween('create_date', [$startTime, $endTime])->where(['type' => 1, 'pay_method' => 2])->sum('record_money');

        // ---------- 会员升级 ---------- //
        // 总金额
        $totalLevelRecord = Memberlevelrecord::whereBetween('create_date', [$startTime, $endTime])->where(['status' => 1])->sum('money');
        // 单数
        $countLevelRecord = Memberlevelrecord::whereBetween('create_date', [$startTime, $endTime])->where(['status' => 1])->count();
        // 余额支付 金额
        $balanceLevelRecord = Memberlevelrecord::whereBetween('create_date', [$startTime, $endTime])->where(['status' => 1, 'pay_method' => 3])->sum('money');
        // 微信支付 金额
        $weixinLevelRecord = Memberlevelrecord::whereBetween('create_date', [$startTime, $endTime])->where(['status' => 1, 'pay_method' => 1])->sum('money');
        // 支付宝支付 金额
        $alipayLevelRecord = Memberlevelrecord::whereBetween('create_date', [$startTime, $endTime])->where(['status' => 1,'pay_method' => 2])->sum('money');

        // ---------- 现金收支 ---------- //

        // 总计
        $totalAmount = $totalOrder + $totalRecharge + $totalLevelRecord;
        $totalBalance = $balanceOrder + $totalLevelRecord;
        $totalWeixin = $weixinOrder + $weixinRecharge + $weixinLevelRecord;
        $totalAlipay = $alipayOrder + $alipayRecharge + $alipayLevelRecord;

        $tableHtml = '';
        $tableHtml .= '<tr>';
            $tableHtml .= '<td><span class="layui-blue">商品销售</span></td>';
            $tableHtml .= '<td>销售额<span class="layui-blue">&nbsp;' . ($totalOrder / 100) . '</span>&nbsp;&nbsp;&nbsp;单数<span class="layui-blue">&nbsp;' . $countOrder . '</span>&nbsp;&nbsp;&nbsp;单均价<span class="layui-blue">&nbsp;' . $averagePrice . '</span></td>';
            $tableHtml .= '<td>' . ($balanceOrder / 100) . '</td>';
            $tableHtml .= '<td>' . ($weixinOrder / 100) . '</td>';
            $tableHtml .= '<td>' . ($alipayOrder / 100) . '</td>';
        $tableHtml .= '</tr>';
        $tableHtml .= '<tr>';
            $tableHtml .= '<td><span class="layui-blue">钱包充值</span></td>';
            $tableHtml .= '<td>充值额<span class="layui-blue">&nbsp;' . ($totalRecharge / 100) . '</span>&nbsp;&nbsp;&nbsp;赠送额<span class="layui-blue">&nbsp;' . ($totalRechargeGift / 100) . '</span>&nbsp;&nbsp;&nbsp;单数<span class="layui-blue">&nbsp;' . $countRecharge . '</span></td>';
            $tableHtml .= '<td>-</td>';
            $tableHtml .= '<td>' . ($weixinRecharge / 100) . '</td>';
            $tableHtml .= '<td>' . ($alipayRecharge / 100) . '</td>';
        $tableHtml .= '</tr>';
        $tableHtml .= '<tr>';
            $tableHtml .= '<td><span class="layui-blue">会员升级</span></td>';
            $tableHtml .= '<td>金额<span class="layui-blue">&nbsp;' . ($totalLevelRecord / 100) . '</span>&nbsp;&nbsp;&nbsp;单数<span class="layui-blue">&nbsp;' . $countLevelRecord . '</span></td>';
            $tableHtml .= '<td>' . ($balanceLevelRecord / 100) . '</td>';
            $tableHtml .= '<td>' . ($weixinLevelRecord / 100) . '</td>';
            $tableHtml .= '<td>' . ($alipayLevelRecord / 100) . '</td>';
        $tableHtml .= '</tr>';
        $tableHtml .= '<tr>';
        /*$tableHtml .= '<td><span class="layui-blue">现金收支</span></td>';
            $tableHtml .= '<td></td>';
            $tableHtml .= '<td></td>';
            $tableHtml .= '<td></td>';
            $tableHtml .= '<td></td>';
        $tableHtml .= '</tr>';*/
        $tableHtml .= '<tr>';
            $tableHtml .= '<td><span class="layui-blue">总计</span></td>';
            $tableHtml .= '<td>' . ($totalAmount / 100) . '</td>';
            $tableHtml .= '<td>' . ($totalBalance / 100) . '</td>';
            $tableHtml .= '<td>' . ($totalWeixin / 100) . '</td>';
            $tableHtml .= '<td>' . ($totalAlipay / 100) . '</td>';
        $tableHtml .= '</tr>';
        /*$tableHtml .= '<tr>';
            $tableHtml .= '<td><span class="layui-blue">营业实收</span></td>';
            $tableHtml .= '<td></td>';
            $tableHtml .= '<td></td>';
            $tableHtml .= '<td></td>';
            $tableHtml .= '<td></td>';
        $tableHtml .= '</tr>';*/

        return $tableHtml;
    }

    /**
     * 商品销量统计 Top5
     */
    protected function salesStatistics(){
        $orderitems = Orderitem::whereTime('create_date', 'month')->group('product_id')->field('product_id, product_name, count')->limit(0, 5)->order('count DESC')->select();
        $totalSales = 0;
        $statistics = [];
        foreach ($orderitems as $item) {
            $productName = Product::where('id', $item['product_id'])->value('name');
            $productName && $item['product_name'] = $productName;

            $totalSales += $item['count'];
            $statistics['name'][] = $item['product_name'];
            $statistics['value'][] = $item['count'];
        }

        $data = [
            'data' => $orderitems,
            'totalSales' => $totalSales,
            'statistics' => json_encode($statistics)
        ];

        return $data;
    }

    /**
     * 商品交易额统计 Top5
     */
    protected function tradeStatistics(){
        //$orderitems = Orderitem::whereTime('create_date', 'month')->group('product_id')->field('product_id, product_name, count')->limit(0, 5)->order('total_price DESC')->select();
        $startMonth = date("Y-m-01");
        $endMonth = date('Y-m-d', strtotime(date("Y-m-01 23:59:59")." +1 month -1 day"));
        $sql = "SELECT `product_id`, `product_name`, sum(price*count) AS total_price FROM `order_item` WHERE `create_date` BETWEEN '{$startMonth}' AND '{$endMonth}' GROUP BY `product_id` ORDER BY `total_price` DESC LIMIT 0,5";
        $orderitems = Db::query($sql);

        $totalAmount = 0;
        $statistics = [];
        foreach ($orderitems as &$item) {
            $productName = Product::where('id', $item['product_id'])->value('name');
            $productName && $item['product_name'] = $productName;

            $totalAmount += $item['total_price'];
            $statistics['name'][] = $item['product_name'];
            $statistics['value'][] = $item['total_price'];
        }

        $data = [
            'data' => $orderitems,
            'totalAmount' => $totalAmount,
            'statistics' => json_encode($statistics)
        ];

        return $data;
    }

    /**
     * 运营统计
     */
    protected function operationStatistics(){
        // 今日交易额
        $todayAmount = Order::whereTime('create_date', 'today')->sum('total');
        // 今日订单数
        $todayOrder = Order::whereTime('create_date', 'today')->count();
        // 今日新增会员
        $todayMember = Member::whereTime('create_date', 'today')->count();

        $startTime = date('Y-m-d', time() - 3600*24*10); // 10天前
        $endTime = date('Y-m-d', time() + 3600*24*10); // 10天后
        $length = 20;
        $day = [];
        $countMember = [];
        $countOrder = [];
        $totalAmount = [];
        for($i=0; $i <= $length; $i++){
            $daytime = strtotime($startTime) + ($i*86400);
            $startDay = date("Y-m-d 00:00:00", $daytime);
            $endDay = date("Y-m-d 23:59:59", $daytime);

            $day[] = date('Y-m-d', $daytime);
            $countMember[] = Member::whereBetween('create_date', [$startDay, $endDay])->count();
            $countOrder[] = Order::whereBetween('create_date', [$startDay, $endDay])->count();
            $amount = Order::whereBetween('create_date', [$startDay, $endDay])->sum('total');
            $totalAmount[] = $amount / 100;
        }
        $statistics = [
            'day' => $day,
            'countMember' => $countMember,
            'countMember' => $countOrder,
            'totalAmount' => $totalAmount,
        ];

        $data = [
            'todayAmount' => $todayAmount ? $todayAmount / 100 : 0,
            'todayOrder' => $todayOrder,
            'todayMember' => $todayMember,
            'statistics' => json_encode($statistics)
        ];

        return $data;
    }
}